package design.pattern.Lu06ProxyPattern;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @program day01
 * @description: cglib动态代理
 * @author: zhanglu
 * @create: 2019-12-01 22:32:00
 *
 * 不需要实现接口
 */
public class CglibDynamicProxy {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(HelloConcrete.class);
        enhancer.setCallback(new MyMethodInterceptor());
        HelloConcrete hello = (HelloConcrete)enhancer.create();
        System.out.println(hello.sayHello("I love you!"));
    }

}

class HelloConcrete{
    public String sayHello(String str) {
        System.out.println(" ---> 执行中");
        return " ---> 返回值 " + str;
    }
}

class MyMethodInterceptor implements MethodInterceptor {

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        preHandle();

        Object obj = methodProxy.invokeSuper(o, objects);

        endHandle();

        return obj;
    }

    private void preHandle() {
        System.out.println(" ---> preHandle");
    }

    private void endHandle() {
        System.out.println(" ---> endHandle");
    }

}